<template>
  <view class="container">
    <scroll-view
      v-for="(level, index) in levels"
      :key="index"
      scroll-y
      class="level"
    >
      <view
        class="item"
        v-for="item in getLevelData(index)"
        :key="item.id"
        :class="{ active: item.id === activeIds[level] }"
        @click="handleItemClick(level, item)"
      >
        <text class="item-name">{{ item.name }}</text>
      </view>
    </scroll-view>
  </view>
</template>
  
<script>
const LEVELS = ["level1", "level2", "level3"];
const ALL_ITEMS = {
  level1: { id: "all1", name: "不限" },
  level2: { id: "all2", name: "不限" },
  level3: { id: "all3", name: "不限" },
};

export default {
  name: "AreaScreen",

  props: {
    checkIds: { type: Array, default: () => [] },
    list: { type: Array, default: () => [] },
    showAllOption: { type: Boolean, default: true },
  },

  data() {
    return {
      levels: LEVELS,
      activeIds: Object.fromEntries(LEVELS.map((level) => [level, ""])),
      currentSelections: Object.fromEntries(
        LEVELS.map((level) => [level, null])
      ),
    };
  },

  computed: {
    levelData() {
      return {
        level1: this.showAllOption
          ? [{ id: "all1", name: "不限" }, ...this.list]
          : [...this.list],
        level2: this.getChildData("level1", "all1", "level2"),
        level3: this.getChildData("level2", "all2", "level3"),
      };
    },
  },

  watch: {
    list: {
      immediate: true,
      handler(newData) {
        if (newData?.length) this.initializeSelections();
      },
    },
    checkIds: {
      immediate: true,
      handler(newIds, oldIds) {
        if (!oldIds?.length || !newIds?.length) this.initializeSelections();
      },
    },
  },

  methods: {
    getLevelData(index) {
      return this.levelData[LEVELS[index]] || [];
    },

    getChildData(parentLevel, allId, currentLevel) {
      const parent = this.currentSelections[parentLevel];
      if (!parent || (this.showAllOption && parent.id === allId)) return [];
      const children = parent.children || [];
      return this.showAllOption
        ? [ALL_ITEMS[currentLevel], ...children]
        : children;
    },

    initializeSelections() {
      if (!this.list?.length) return;

      this.resetAllSelections();

      if (!this.checkIds?.length) {
        const defaultItem = this.showAllOption
          ? ALL_ITEMS.level1
          : this.list[0];
        if (defaultItem) this.handleLevelChange("level1", defaultItem);
        return;
      }

      if (this.checkIds.length === 3) {
        this.initializeFullPath();
        return;
      }

      const selectedAllId = this.checkIds.find((id) =>
        String(id).startsWith("all")
      );
      if (selectedAllId && this.showAllOption) {
        this.initializeAllSelection(selectedAllId);
        return;
      }

      this.initializeSingleSelection(this.checkIds[0]);
    },

    initializeFullPath() {
      const [l1Id, l2Id, l3Id] = this.checkIds;
      const path = [];

      const l1 = this.list.find((item) => item.id === l1Id);
      if (!l1)
        return this.handleLevelChange(
          "level1",
          this.showAllOption ? ALL_ITEMS.level1 : this.list[0]
        );
      path.push(l1);

      const l2 = l1.children?.find((item) => item.id === l2Id);
      if (!l2) return this.setPath(path, "level2");
      path.push(l2);

      const l3 = l2.children?.find((item) => item.id === l3Id);
      if (!l3) return this.setPath(path, "level3");
      path.push(l3);

      this.setPath(path, "level3");
    },

    initializeAllSelection(selectedAllId) {
      const levelMap = { all1: 1, all2: 2, all3: 3 };
      const targetLevel = levelMap[selectedAllId];

      const path = [];
      let current = this.list[0];
      for (let i = 1; i < targetLevel && current; i++) {
        path.push(current);
        current = current.children?.[0];
      }
      this.setPath(path, LEVELS[targetLevel - 1]);
    },

    initializeSingleSelection(selectedId) {
      let path = [];
      this.list.some((l1) => {
        return l1.children?.some((l2) => {
          return l2.children?.some((l3) => {
            if (l3.id === selectedId) {
              path = [l1, l2, l3];
              return true;
            }
            return false;
          });
        });
      });
      if (path.length) this.setPath(path, "level3");
    },

    setPath(path, finalLevel) {
      LEVELS.forEach((level, i) => {
        const item =
          path[i] ||
          (i === 0 && !this.showAllOption
            ? this.getLevelData(i)[0]
            : this.showAllOption
            ? ALL_ITEMS[level]
            : null);
        if (item) this.handleLevelChange(level, item, i < path.length);
      });
    },

    handleItemClick(level, item) {
      level === "level3"
        ? this.handleLevel3Select(item)
        : this.handleLevelChange(level, item);
    },

    handleLevelChange(level, item, skipAutoSelect = false) {
      if (!item) return;

      // 设置当前选择
      this.activeIds[level] = item.id;
      this.currentSelections[level] = item;

      // 重置后续级别
      this.resetLowerLevels(level);

      // 触发事件
      this.emitChange();

      // 如果是"不限"选项（仅当 showAllOption 为 true 时有效），直接返回
      if (this.showAllOption && String(item.id).startsWith("all")) {
        return;
      }

      // 如果需要跳过自动选择，则返回
      if (skipAutoSelect) return;

      // 自动选择下一级（如果有子级）
      const nextLevel = LEVELS[LEVELS.indexOf(level) + 1];
      if (nextLevel && item.children?.length) {
        const nextItem = this.showAllOption
          ? ALL_ITEMS[nextLevel]
          : item.children[0];
        if (nextItem) this.handleLevelChange(nextLevel, nextItem);
      }
    },

    handleLevel3Select(item) {
      this.activeIds.level3 = item.id;
      this.currentSelections.level3 = item;

      if (this.showAllOption && item.id === "all3") return this.emitChange();

      const MAX_SELECTION = 10;
      const currentPath = this.getCurrentPath();
      const isSelected =
        this.checkIds.length === 3 && this.checkIds[2] === item.id;
      const names = LEVELS.map(
        (level) => this.currentSelections[level]?.name || ""
      );

      if (!isSelected && this.checkIds.length >= MAX_SELECTION) {
        uni.showToast({
          title: `最多只能选择${MAX_SELECTION}个区域`,
          icon: "none",
        });
        return;
      }

      this.$emit("changeCheck", isSelected ? [] : currentPath, names);
    },

    resetAllSelections() {
      LEVELS.forEach((level) => {
        this.activeIds[level] = "";
        this.currentSelections[level] = null;
      });
    },

    resetLowerLevels(fromLevel) {
      const startIndex = LEVELS.indexOf(fromLevel) + 1;
      for (let i = startIndex; i < LEVELS.length; i++) {
        this.activeIds[LEVELS[i]] = "";
        this.currentSelections[LEVELS[i]] = null;
      }
    },

    getCurrentPath() {
      return LEVELS.map((level) => this.currentSelections[level]?.id || "");
    },

    emitChange() {
      const ids = this.getCurrentPath();
      const names = LEVELS.map(
        (level) => this.currentSelections[level]?.name || ""
      );
      this.$emit("changeCheck", ids, names);
    },
  },
};
</script>
  
<style lang="scss" scoped>
.container {
  height: 704rpx;
  display: flex;
  background-color: #fff;

  .level {
    width: 33.33%;
    height: 100%;
    background-color: #f5f5f5;
    border-right: 1px solid #eee;

    &:last-child {
      border-right: none;
    }

    .item {
      height: 88rpx;
      font-size: 28rpx;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      box-sizing: border-box;

      &.active {
        background-color: #fff;
        color: $theme-color;
        font-weight: 500;
      }

      &:active {
        background-color: #f0f0f0;
      }

      .item-name {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }
}
</style>